﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace Server
{
    class Program
    {
        static IPAddress iPAddress;
        static TcpListener listener;
        static Socket socket;
        static string ip;

        static void Main(string[] args)
        { 
            Console.WriteLine($"Server [Version {Utils.GetVersion()}]\n");

            loop:
            {
                ServerWrite("Input ip address: ");
                ip = Console.ReadLine();
            }

            try
            {
                iPAddress = IPAddress.Parse(ip);  // 把IP地址转换为IPAddress的实例
                listener = new TcpListener(iPAddress, 8888); // 初始化监听器， 端口为8888
                // 开始监听服务器端口
                listener.Start();

                // 输出服务器启动信息
                Console.WriteLine($"Start service at {listener.LocalEndpoint} on port 8888: ");
                Console.WriteLine("Wait for connection...\n");
            }
            catch(FormatException)
            {
                Console.WriteLine("Invalid Format\n");
                goto loop;
            }
            catch(ArgumentNullException)
            {
                Console.WriteLine("Argument should not be null\n");
                goto loop;
            }

            listen:
            {
                // 等待处理接入连接请求 
                socket = listener.AcceptSocket();
                Console.WriteLine("Connection from " + socket.RemoteEndPoint);
            }

            //接收命令
            while (socket.Connected)
            {
                try
                { 
                    //接收返回信息
                    byte[] buffer = new byte[100];
                    int receiveNumber = socket.Receive(buffer);

                    //Client断开连接
                    if (receiveNumber == 0)
                    {
                        goto listen;
                    }

                    string command = Encoding.UTF8.GetString(buffer, 0, receiveNumber);
                    ServerWriteLine($"Command from client {socket.RemoteEndPoint}: {command}");
                    var keys = command.Split(',').ToList();
                    
                    foreach (var item in keys)
                    {
                        if (item.Equals("173"))
                        {
                            Mouse.Down(System.Windows.Input.MouseButton.Left);
                            Mouse.Up(System.Windows.Input.MouseButton.Left);
                        }
                        else if (item.Equals("174"))
                        {
                            Mouse.Down(System.Windows.Input.MouseButton.Right);
                            Mouse.Up(System.Windows.Input.MouseButton.Right);
                        }
                        else
                        {
                            //KeyHelper.SendKey(item);
                            int keyCode = Convert.ToInt32(item);
                            System.Windows.Input.Key key = (System.Windows.Input.Key)keyCode;
                            Keyboard.Press(key);
                            Keyboard.Release(key);
                        }
                    }

                    //var key = (System.Windows.Input.Key)(Convert.ToInt32(command));
                    //KeyHelper.SendKey(command);
                    
                    //Keyboard.Press(key);
                    //Keyboard.Release(key);

                    //string text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
                    //int index = new Random().Next(0, text.Length - 1);
                    //Keyboard.Type(text.Substring(index,1));

                    //Mouse.MoveTo(new System.Windows.Point(new Random().Next(0,700), new Random().Next(0,700)));
                    //Mouse.Down(System.Windows.Input.MouseButton.Right);
                    //Mouse.Up(System.Windows.Input.MouseButton.Right);
                    
                }
                catch (SocketException e)
                {
                    Console.WriteLine($"{e.ErrorCode} {e.Message}");
                }
            }

            goto listen;
        }
         

        static void SendKey()
        {
            int keyCode = 120;
            System.Windows.Input.Key key = (System.Windows.Input.Key)keyCode;
            Keyboard.Press(key);
            Keyboard.Release(key);
        }

        static List<int> StringToListInt(string command)
        {
            string[] cmds = command.Split(',');
            List<int> keys = new List<int>();
            for (int i = 0; i < cmds.Length; i++)
            {
                keys.Add(Convert.ToInt32(cmds[i]));
            }
            return keys;
        }

        static void ServerWriteLine(string message)
        {
            Console.WriteLine($"Server> {message}");
        }

        static void ServerWrite(string message)
        {
            Console.Write($"Server> {message}");
        }

        static void CloseSocket()
        {
            if (socket == null ||
                !socket.Connected)
            {
                return;
            }
            
            try
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
            catch
            {

            }
        }
    }
}
